<template>
  <ElDrawer v-model="opened" :title="formType" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon :disabled="isView">
      <ElFormItem label="分类字典类型" :label-width="labelWidth" prop="category" v-if="!isEdit && form.parentId === 0">
        <el-select v-model="form.category" :clearable="true" :fit-input-width="true" @change="filterCategoryDict">
          <el-option v-for="item in TbyCategoryDict.Category" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="分类字典类型" :label-width="labelWidth" prop="category" v-if="isEdit || form.parentId !== 0">
        <ElInput v-model="form.categoryLabel" :disabled="true" />
      </ElFormItem>
      <ElFormItem label="上级分类" :label-width="labelWidth" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          placeholder="选择上级分类"
          :data="parentOptions"
          filterable
          check-strictly
          :disabled="isView"
          :render-after-expand="false" />
      </ElFormItem>
      <ElFormItem label="编码" :label-width="labelWidth" prop="code">
        <ElInput v-model="form.code" />
      </ElFormItem>
      <ElFormItem label="名称" :label-width="labelWidth" prop="name">
        <ElInput v-model="form.name" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton v-if="!isView" type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, unref, computed } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance } from 'element-plus'
import {
  TbyCategoryDict,
  getCategoryDictDetail,
  saveOrUpdateCategoryDict,
  optionsCategoryDict,
  getCategoryLabel,
  codeExist
} from '@api/tby/common/categoryDict'
import { FormType } from '@/enums'
const labelWidth = 150
const opened = ref(false)
const loading = ref(true)
const formType = ref<FormType>()
const formRef = ref<FormInstance>()
const form = ref<Partial<TbyCategoryDict.Form>>({})
const parentOptions = ref<OptionType[]>([])

onMounted(async () => {
  console.log('进来了')
})

// 是否查看
const isView = computed(() => {
  return formType.value === FormType.VIEW
})

// 是否新增
const isAdd = computed(() => {
  return formType.value === FormType.ADD
})

const isEdit = computed(() => {
  return formType.value === FormType.EDIT
})

const validateCode = (rule: any, value: any, callback: any) => {
  codeExist(value, form.value?.id).then(resp => {
    if (!value) {
      return callback()
    }
    if (resp.data) {
      callback(new Error('改编码已存在'))
    } else {
      callback()
    }
  })
}

const rules = reactive<FormRules>({
  category: [{ required: true, message: '请选择分类字典类型', trigger: 'blur' }],
  code: [
    { required: true, message: '请输入编码', trigger: 'blur' },
    { validator: validateCode, trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请选择名称', trigger: 'blur' },
    { max: 20, message: '名称最大32个字符', trigger: 'blur' }
  ]
})

const open = async (type: FormType, parentId: number, category?: string, id?: number) => {
  form.value = {}
  formType.value = type
  opened.value = true
  filterCategoryDict(category)
  formRef.value?.clearValidate()
  if (isAdd.value) {
    loading.value = false
    form.value.parentId = parentId
    if (category) {
      form.value.category = category
      form.value.categoryLabel = getCategoryLabel(category)
    }
    return
  }
  try {
    const { data } = await getCategoryDictDetail(id!)
    loading.value = false
    form.value = data
    form.value.categoryLabel = getCategoryLabel(form.value.category)
  } finally {
    loading.value = false
  }
}

async function filterCategoryDict(category?: string) {
  let query: TbyCategoryDict.Query = {
    current: 1,
    size: 500
  }
  if (category) {
    query.category = category
  }
  const { data } = await optionsCategoryDict(query)
  parentOptions.value = [{ value: 0, label: '顶级分类', children: data }]
}

function close() {
  loading.value = true
  opened.value = false
  form.value = {}
}

const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    const formData = { ...unref(form) }
    saveOrUpdateCategoryDict(formData).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
